﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Reflection;

namespace FlexPlatform.GeneralUse
{
    public class ReflectionHelper
    {
        public static LambdaExpression GetLambda<baseType>(Expression<Func<baseType, dynamic>> memberPath)
        {
            return memberPath;
        }

        public static LambdaExpression GetLambda(PropertyInfo propertyInfo)
        {
            var instance = Expression.Parameter(propertyInfo.DeclaringType, "i");
            var property = Expression.Property(instance, propertyInfo);
            var convert = Expression.TypeAs(property, propertyInfo.ReflectedType);
            return Expression.Lambda(convert, instance);
        }

        public static List<PropertyInfo> GetPropertyInfos<T>()
        {
            List<PropertyInfo> propertyInfos;

            propertyInfos = typeof(T).GetProperties().ToList <PropertyInfo>();

            return propertyInfos;
        }

        public static List<PropertyInfo> GetPropertyInfos(Type theType)
        {
            List<PropertyInfo> propertyInfos;

            propertyInfos = theType.GetProperties().ToList<PropertyInfo>();

            return propertyInfos;
        }

        public static List<LambdaExpression> GetPropertyLambdas<T>()
        {
            List<PropertyInfo> propertyInfos = GetPropertyInfos<T>();
            List<LambdaExpression> propertyExpressions = new List<LambdaExpression>();

            foreach(var propertyInfo in propertyInfos)
            {
                propertyExpressions.Add(GetLambda(propertyInfo));
            }

            return propertyExpressions;
        }

        public static string GetPropertyName(LambdaExpression propertyLambda)
        {
            var body = propertyLambda.Body;

            if (body is MemberExpression)
            {
                return ((MemberExpression)body).Member.Name;
            }

            return null;
        }
    }
}
